﻿using System.Linq;
using System.Xml.Linq;
using PengSW.NotifyPropertyChanged;
using PengSW.ObservableCollectionHelper;
using PengSW.XmlHelper;
using static PengSW.XmlHelper.XmlLinqHelper;

namespace PengSW.XmlImport
{
    public class ReplaceRule : NotifyPropertyChangedObject, IXmlSeriable
    {
        public ReplaceRule(ImportRule aImportRule)
        {
            ImportRule = aImportRule;
        }

        public ImportRule ImportRule { get; }

        public string Id { get { return _Id; } set { SetValue(ref _Id, string.IsNullOrWhiteSpace(value) ? "未命名规则" : value, nameof(Id)); } }
        private string _Id = "未命名规则";

        public ObservableCollectionEx<ReplacePattern> ReplacePatterns { get; } = new ObservableCollectionEx<ReplacePattern>();

        public void ReadFromXml(XElement aXElement)
        {
            if (aXElement == null) return;
            Id = aXElement.GetAttributeValue(nameof(Id), null);
            ReplacePatterns.Clear();
            foreach (XElement aChildXElement in aXElement.Elements("Replace"))
            {
                ReplacePattern aReplacePattern = new ReplacePattern(this);
                aReplacePattern.ReadFromXml(aChildXElement);
                ReplacePatterns.Add(aReplacePattern);
            }
        }

        public XElement CreateXElement(string aXmlNodeName)
        {
            return new XElement(aXmlNodeName, CreateXAttribute(nameof(Id), Id), from r in ReplacePatterns select r.CreateXElement("Replace"));
        }

        public string Replace(string aValue)
        {
            foreach (ReplacePattern aReplacePattern in ReplacePatterns)
            {
                aValue = aReplacePattern.Replace(aValue);
            }
            return aValue;
        }
    }
}
